package com.neu.yth.nepBackend.auth.jwt;

import com.neu.yth.nepBackend.entity.Member;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName tokenUtils
 * @Description
 * @Author YTH
 * @Date 2024-06-20 14:28
 */
public class TokenUtils {
    private static final String ID = "id";
    private static final String NUMBER = "number";
    private static final String PASSWORD = "password";
    private static final Object ROLEID = "roleId";
    private static final byte[] secretKey = "neusoft,123!neusoft,123!neusoft,123!".getBytes();


    public static String generateToken(Member member) {
        Map map = new HashMap();
        map.put(ID, member.getMemId());
        map.put(ROLEID, member.getRoleId());
        map.put(PASSWORD, member.getMemPwd());
        map.put(NUMBER, member.getMemNumber());
        return Jwts.builder()
                .setSubject("auth")
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)) // 1 hour
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public static Member parseToken(String token) {
//        如果Token被篡改，那么 以下语句异常
        Claims body = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
        Member member = new Member();
        member.setMemId((Integer) body.get(ID));
        member.setRoleId((Integer) body.get(ROLEID));
        member.setMemPwd((String) body.get(PASSWORD));
        member.setMemNumber((String) body.get(NUMBER));
        return member;
    }

}
